#include <bits/stdc++.h>
using namespace std;
int dx[4]= {1,0,-1,0},dy[4]= {0,1,0,-1};
int a[10][10],book[10][10][8];
int n,m,sx,sy,ans=INT_MAX;
void dfs(int x,int y,int step,int hp) {
	if(a[x][y]==3) {
		ans=step;
		return;
	}
	if(a[x][y]==4)   hp=6;
	if(hp<=1||step>=ans||a[x][y]==0||step>=book[x][y][hp])  return;
	book[x][y][hp] = step;
	for(int i=0; i<4; i++) {
		int nx=x+dx[i],ny=y+dy[i];
		dfs(nx,ny,step+1,hp-1);
	}
	return;
}
int main() {
	cin >> n >> m;
	for(int i=1; i<=n; i++) {
		for(int j=1; j<=m; j++) {
			cin>>a[i][j];
			if(a[i][j]==2)sx=i,sy=j;
		}
	}
	memset(book,0x3f,sizeof(book));
	dfs(sx,sy,0,6);
	if(ans<INT_MAX)cout<<ans;
	else cout<<"-1";
	return 0;
}

